//
//  ListImageViewController.m
//  DemoMeshtiles
//
//  Created by MAC on 7/19/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ListImageViewController.h"
#import "CustomListCellCell.h"
#import "GridViewViewController.h"
@interface ListImageViewController ()
@property BOOL isScrollDetecd;
@end

@implementation ListImageViewController
@synthesize photoData=_photoData;
@synthesize isScrollDetecd;

@synthesize listPhotoStream=_listPhotoStream;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated {
   self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [_photoData removeAllObjects];
        if ([photoStreams count]>0) {
            
            if ([_listPhotoStream count]<[photoStreams count]) {
                //gen link from 4 image
                NSMutableString *link=[[NSMutableString alloc] initWithString:@"http://ec2-107-20-246-0.compute-1.amazonaws.com/api/View/getListPhotoDetail?list_photo_id="];
                //add 4 photo ID vao link
                for (int i=[_listPhotoStream count];i<4;i++) {
                    NSDictionary *photo=[photoStreams objectAtIndex:i];
                    NSString *photoId=[photo objectForKey:@"photo_id"];
                    if (i==3) [link appendFormat:@"%@",photoId];
                    else [link appendFormat:@"%@,",photoId];
                }
                [link appendFormat:@"&user_id=1d6311db-6a2e-4362-a3c3-2a7a7814f7a4"];
                NSLog(@"Gen link: %@",link);
                
                //uses asihttp
                NSURL *url = [NSURL URLWithString:link] ;
                ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
                [request setRequestMethod:@"POST"];
                [request setDelegate:self];
                [request startAsynchronous];
            } else {
                //request more
            }
            
        }
    
   
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
    
    NSData *responseData = [request responseData];
    SBJsonParser *parser=[[SBJsonParser alloc] init];
    NSString *jsonString=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  //  NSLog(@"Data 4 photo: %@",jsonString);
    NSDictionary *status=(NSDictionary *)[parser objectWithString:jsonString error:nil];
    if ([status objectForKey:@"is_success"]!=0) {//Load photo to array if success
        NSArray*array=[status objectForKey:@"photo"];
        [_photoData addObjectsFromArray:array];
        NSLog(@"So phan tu photoData: %d",[_photoData count]);
    } 
[self.tableView reloadData];
    isScrollDetecd=NO;
   
    [status release];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
     [self.tableView setBackgroundColor:[UIColor colorWithRed:237*1.0f/255 green:234*1.0f/255 blue:229*1.0f/255 alpha:1]];
    

    _photoData =[[NSMutableArray alloc] init];
    _listPhotoStream=[[NSMutableArray alloc] init];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return [_photoData count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
//    NSLog(@"So cell cua bang list: %d",[_photoData count]);
//    return [_photoData count];
    //dem so comment cua cell
    
    NSDictionary *dict=[_photoData objectAtIndex:section];
    NSArray *commentArray=[dict objectForKey:@"comment"];
    //NSLog(@"Section %d, row = %d",section,[commentArray count]+1);
    return ([commentArray count]+1);
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *SimpleTableIdentifier = @"PhotoCell";
    static NSString *CommentTableIdentifier=@"CommentCell";
    if ([indexPath row]==0) {//photo cell
        CustomListCellCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
        NSDictionary *dict=(NSDictionary*)[_photoData objectAtIndex:[indexPath section]];
        if (cell == nil) {
            
            
            cell=[[CustomListCellCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier withData:dict];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }  
        [cell setCellData:dict];
        return cell; 
    } else {
        NSDictionary *dict=[_photoData objectAtIndex:[indexPath section]];
        NSArray *commentArray=[dict objectForKey:@"comment"];
         CommentCell *cell=[tableView dequeueReusableCellWithIdentifier:CommentTableIdentifier];
        if (cell == nil) {
            
            cell=[[CommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CommentTableIdentifier];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }   
        [cell setCellData:[commentArray objectAtIndex:([indexPath row]-1)]];
                                                       
        return cell;
    }
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    int row=[indexPath row];
    if (row==0) {
        return 432;
    } else {
        CGRect commentRect = CGRectMake(70, 30, 310-70, 15);
        UILabel *comment = [[[UILabel alloc] initWithFrame:commentRect] autorelease]; 
        comment.textColor=[UIColor grayColor];
        comment.font=[UIFont systemFontOfSize:12];
        //Update comment
        NSDictionary *dict=[_photoData objectAtIndex:[indexPath section]];
        NSArray *commentArr=[dict objectForKey:@"comment"];
        NSDictionary *commentObj=[commentArr objectAtIndex:([indexPath row]-1)];
        NSString *beforeDecodeStr=[commentObj objectForKey:@"content"];       
        NSString *commentStr=[beforeDecodeStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        CGSize maximumLabelSize = CGSizeMake(296,9999);
        CGSize expectedLabelSize = [commentStr sizeWithFont:comment.font 
                                          constrainedToSize:maximumLabelSize 
                                              lineBreakMode:comment.lineBreakMode]; 
        
        //adjust the label the the new height.
        CGRect newFrame = comment.frame;
        newFrame.size.height = expectedLabelSize.height;
        comment.frame = newFrame;
        comment.text=commentStr;
        //
        int cellHeight=30+(newFrame.size.height)+10;//bonus 10
        if (cellHeight<70) cellHeight=70;
        return cellHeight;
    
    }
        
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}
- (void)scrollViewDidScroll:(UIScrollView *)aScrollView {
    CGPoint offset = aScrollView.contentOffset;
    CGRect bounds = aScrollView.bounds;
    CGSize size = aScrollView.contentSize;
    UIEdgeInsets inset = aScrollView.contentInset;
    float y = offset.y + bounds.size.height - inset.bottom;
    float h = size.height;
//     NSLog(@"offset: %f", offset.y);   
//     NSLog(@"content.height: %f", size.height);   
//     NSLog(@"bounds.height: %f", bounds.size.height);   
//     NSLog(@"inset.top: %f", inset.top);   
//     NSLog(@"inset.bottom: %f", inset.bottom);   
//     NSLog(@"pos: %f of %f", y, h);
    
    float reload_distance = 10;
    if(y > h + reload_distance) {
        
        if (isScrollDetecd==NO)
        isScrollDetecd=YES;
    }

}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (isScrollDetecd==YES) {
        //Load more
        if ([photoStreams count]>0) {
            
            if ([_photoData count]<[photoStreams count]) {
                NSLog(@"Thuc hien Load more");
                //gen link from 4 image
                NSMutableString *link=[[NSMutableString alloc] initWithString:@"http://ec2-107-20-246-0.compute-1.amazonaws.com/api/View/getListPhotoDetail?list_photo_id="];
                //add 4 photo ID vao link
                NSLog(@"Gen link tu photo thu %d,%d,%d",[_photoData count],[_photoData count]+1,[_photoData count]+2);
                for (int i=[_photoData count];i<[_photoData count]+4;i++) {
                    
                    NSDictionary *photo=[photoStreams objectAtIndex:i];
                    NSString *photoId=[photo objectForKey:@"photo_id"];
                    if (i==3) [link appendFormat:@"%@",photoId];
                    else [link appendFormat:@"%@,",photoId];
                }
                [link appendFormat:@"&user_id=1d6311db-6a2e-4362-a3c3-2a7a7814f7a4"];
              //NSLog(@"Gen link: %@",link);
                
                //Use ASIHTTP request Data
                NSURL *url = [NSURL URLWithString:link];
                ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
                [request setRequestMethod:@"POST"];
                [request setDelegate:self];
                [request startAsynchronous];
                
                
            } else {
                //request more
            }
            
        }

        
    }
}


@end
